package com.google.code.p.restrpc.http;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import com.google.code.p.restrpc.util.IOUtils;

public class HttpResponseWrapper implements HttpClientResponse {
    
    private HttpResponse httpResponse;
    
    private HttpHeaders headers;
    
    public HttpResponseWrapper(HttpResponse response) throws IOException {
        super();
        this.httpResponse = response;
    }
    
    public HttpStatus getStatusCode() throws IOException {
        return HttpStatus.valueOf(getStatusCodeValue());
    }
    
    public int getStatusCodeValue() throws IOException {
        return this.httpResponse.getStatusLine().getStatusCode();
    }
    
    public String getStatusText() throws IOException {
        return this.httpResponse.getStatusLine().getReasonPhrase();
    }
    
    public HttpHeaders getHeaders() {
        if (this.headers == null) {
            this.headers = new HttpHeaders();
            for (Header header : this.httpResponse.getAllHeaders()) {
                this.headers.addHeader(header.getName(), header.getValue());
            }
        }
        return this.headers;
    }
    
    public InputStream getBody() throws IOException {
        HttpEntity entity = this.httpResponse.getEntity();
        return entity != null ? entity.getContent() : null;
    }
    
    public byte[] getBodyAsByteArray() throws IOException {
        InputStream responseBody = getBody();
        if (responseBody != null) {
            return IOUtils.copyToByteArray(responseBody);
        }
        return new byte[0];
    }
    
    public String getBodyAsString() throws IOException {
        //TODO add encoding
        return new String(getBodyAsByteArray());
    }
    
    public void close() {
        HttpEntity entity = this.httpResponse.getEntity();
        if (entity != null) {
            try {
                EntityUtils.consume(entity);
            }
            catch (IOException e) {
            }
        }
    }
    
}
